package com.sservice.web.exception;

import com.alibaba.fastjson.JSON;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 错误信息统一处理 对未处理的错误信息做一个统一处理
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {
        logger.error("[==SSERVICE==]访问" + request.getRequestURI() + " 发生错误, 错误信息:" + ex.getMessage());
        try {
            PrintWriter writer = response.getWriter();
            BaseResult<Object> result = new BaseResult<Object>(false,
                    ex.getMessage(), 500);
            writer.write(JSON.toJSONString(result));
            writer.flush();
        } catch (Exception e) {
            logger.error("Exception:", e);
        }

        return null;
    }
}
